package club.justwill.single.persistence.store;

import club.justwill.single.impl.ToolsImpl;
import club.justwill.single.persistence.document.MobileAuthCode;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Created by xiangnan on 16-1-14.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class MobileAuthCodeStore extends MongoDbStore<MobileAuthCode> {
    public List<MobileAuthCode> searchActiveCodes(String number) {

        List list=mongoTemplate.find(Query.query(Criteria.where("mobile").is(number).and("expiry").gt(new Date())), MobileAuthCode.class);
        if(!ToolsImpl.isEmpty(list)){
            mongoTemplate.remove(Query.query(Criteria.where("expiry").gt(new Date())), MobileAuthCode.class);
        }
        return mongoTemplate.find(Query.query(Criteria.where("mobile").is(number).and("expiry").gt(new Date())), MobileAuthCode.class);
    }

    public void remove(String mobile){
        mongoTemplate.remove(Query.query(Criteria.where("mobile").is(mobile)), MobileAuthCode.class);
    }

    public List<MobileAuthCode> searchCodesByMobile(String number){
        return mongoTemplate.find(Query.query(Criteria.where("mobile").is(number)), MobileAuthCode.class);
    }


    @Scheduled(fixedDelay = 30*60*1000)
    public void removeCodes() {
        Date date = new Date();
        long currentTime = date.getTime();
        currentTime = currentTime - 30*60*1000;
        mongoTemplate.remove(Query.query(Criteria.where("expiry").lt(new Date(currentTime))), MobileAuthCode.class);
    }
}

